package org.adg.code.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.adg.code.model.SaveTemplateValues;
import org.adg.code.model.TemplateMultiValues;
import org.adg.code.service.TemplateManager;
import org.adg.code.service.TemplateManagerImpl;

public class TemplateController {

	/*returns a list which contains 2 resultset object 1 contains the reporttypes and the other contains the uitypes*/
	public ArrayList<Object> getTemplateOtions(HttpServletRequest request, HttpServletResponse response)
	{
		TemplateManager tm=new TemplateManagerImpl();
		return tm.getTemplateOtions();
	}
	
	/*gets the values entered from the jsp to create a new template saves the values to database*/
	/*and created the template file*/
	public boolean saveTemplate(HttpServletRequest request, HttpServletResponse response)
	{
		String nor=(String)request.getParameter("rangeCount");
		int numofrows=Integer.parseInt(nor);
		String keyword,rptypename,uitype;
	
		SaveTemplateValues[] stv=new SaveTemplateValues[numofrows+1];
		TemplateMultiValues[] tmv=new TemplateMultiValues[numofrows+1];
		for(int k=0;k<=numofrows;k++)
		{
			stv[k]=new SaveTemplateValues();
		}
		stv[0].setrepname(request.getParameter("rname"));
		stv[0].setrtype(request.getParameter("rtype"));
		stv[0].settfn(request.getParameter("tfname"));
	
		String val="";
		int nov=0;
		
		for(int i=1;i<=numofrows;i++)
		{
				keyword=(String)request.getParameter("firsttext"+i);
				rptypename=(String)request.getParameter("secondtext"+i);
				uitype=(String)request.getParameter("uitype"+i);
				
				stv[i].setKey(keyword);
				stv[i].setrptn(rptypename);
				stv[i].setuitype(uitype);
				
				if(uitype.equalsIgnoreCase("Selectbox")||uitype.equalsIgnoreCase("Radiobutton"))
				{
					nov=Integer.parseInt(request.getParameter("uitype"+i+"nor"));
					
					List<String> l=new ArrayList<String>();
					tmv[i]=new TemplateMultiValues();
					for(int j=1;j<=nov;j++)
					{
						
						val=(String)request.getParameter((i+1)+"firsttext"+j);
						l.add(val);
						
					}
					tmv[i].setList(l);
					i=i+1;
				}
				
		
		}
		TemplateManager tm=new TemplateManagerImpl();
		return tm.saveTemplate(stv,tmv,numofrows);
		
	}
	public boolean tempNameExists(String tfname)
	{
		TemplateManager tm=new TemplateManagerImpl();
		return tm.tempNameExists(tfname);
	}
	public boolean repCatExists(String rname)
	{
		TemplateManager tm=new TemplateManagerImpl();
		return tm.repCatExists(rname);
	}
}
